<template>
  <div>
    <!--音乐上传的组件-->
    <el-upload ref="audioUpload" v-if="isAudio"
               action=""
               :style="avatarStyle"
               class="logo-uploader"
               :show-file-list="false"
               :http-request="handleUpload"
    >
      <div @mouseover="showBtn=true" @mouseout="showBtn=false">
        <i @click.stop="removeAudio" v-show="dialogAudioUrl && showBtn" class="el-icon-close remove-btn"></i>
        <div v-if="dialogAudioUrl" style="height: 180px;width: 320px">
          <img  src="../../assets/3.png" width="80px" height="80px" >
          <span class="label_clas">{{audioName?audioName:name+".mp3"}}</span>
        </div>
        <div v-else>
        <i class="el-icon-service logo-uploader-icon" :style="avatarStyle"></i>
        </div>
      </div>
    </el-upload>
    <!--单图片上传的组件-->
    <!--http-request :覆盖默认的上传行为，可以自定义上传的实现-->
    <el-upload ref="picUpload" v-else
               action=""
               :style="isAvator?avatarStyle_1:avatarStyle"
               class="logo-uploader"
               :show-file-list="false"
               :http-request="handleUpload"
    >
      <div @mouseover="showBtn=true" @mouseout="showBtn=false">
        <div v-if="isAvator">
          <span class="avator_label">更换头像</span>
<!--          <img v-if="dialogImageUrl" :src="dialogImageUrl" :style="avatarStyle_1">-->
          <v-img
                  v-if="dialogImageUrl" :src="dialogImageUrl" :style="avatarStyle_1"
                  aspect-ratio="1"
                  class="grey lighten-2"
          >
            <template v-slot:placeholder>
              <v-layout
                      fill-height
                      align-center
                      justify-center
                      ma-0
              >
                <v-progress-circular indeterminate color="grey lighten-5"></v-progress-circular>
              </v-layout>
            </template>
          </v-img>
        </div>
        <div v-else>
          <i @click.stop="removeSingle" v-show="dialogImageUrl && showBtn" class="el-icon-close remove-btn"></i>
<!--          <img v-if="dialogImageUrl" :src="dialogImageUrl" :style="avatarStyle">-->
          <v-img
                  v-if="dialogImageUrl" :src="dialogImageUrl" :style="avatarStyle"
                  aspect-ratio="1"
                  class="grey lighten-2"
          >
            <template v-slot:placeholder>
              <v-layout
                      fill-height
                      align-center
                      justify-center
                      ma-0
              >
                <v-progress-circular indeterminate color="grey lighten-5"></v-progress-circular>
              </v-layout>
            </template>
          </v-img>
          <i v-else class="el-icon-upload logo-uploader-icon" :style="avatarStyle"></i>
        </div>
      </div>
    </el-upload>


    <!--上传完成后返回的-->
<!--    <v-dialog v-model="show" max-width="500" v-if="isAudio">-->
<!--      <img width="500px" src="../../assets/3.png" alt="">-->
<!--    </v-dialog>-->
    <v-dialog v-model="show" max-width="500" v-else>
      <img width="500px" :src="dialogImageUrl" alt="">
<!--      <v-img-->
<!--              :src="dialogImageUrl"-->
<!--              aspect-ratio="1"-->
<!--              class="grey lighten-2"-->
<!--      >-->
<!--        <template v-slot:placeholder>-->
<!--          <v-layout-->
<!--                  fill-height-->
<!--                  align-center-->
<!--                  justify-center-->
<!--                  ma-0-->
<!--          >-->
<!--            <v-progress-circular indeterminate color="grey lighten-5"></v-progress-circular>-->
<!--          </v-layout>-->
<!--        </template>-->
<!--      </v-img>-->
    </v-dialog>

    <!--进度条-->
    <el-progress :percentage="progress" v-if="progress >0 && progress < 100 && isAudio"></el-progress>
  </div>

</template>

<script>
  import {Upload} from 'element-ui';
  import fileUtil from './fileUtil';
  import Iview from "iview";

  export default {
    name: "vUpload",
    components: {
      Iview,
      elUpload: Upload
    },
    props: {
      url: {
        type: String,
        require: false
      },
      name: {
        type: String
      },
      value: {},
      isAudio: {
        type: Boolean,
        default: true
      },
      isAvator: {
        type: Boolean,
        default: false
      },
      picWidth: {
        type: Number,
        default: 150
      },
      picHeight: {
        type: Number,
        default: 150
      },
      needSignature: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        showBtn: false,
        show: false,
        dialogImageUrl: "",
        dialogAudioUrl: "",
        avatarStyle: {
          width: this.picWidth + 'px',
          height: this.picHeight + 'px',
          'line-height': this.picHeight + 'px'
        },
        avatarStyle_1: {
          width: this.picWidth+ 3 + 'px',
          height: this.picHeight+ 3 + 'px',
          'border-radius': this.picWidth + 'px'
        },
        progress:0,
        audioName:"",
        fileList: [],
      }
    },
    /*mounted是在页面模板挂载完成才被调用*/
    mounted() {
      //this.value 是上传完成后，返回来的值
      if (!this.value || this.value.length <= 0) {
        return;
      }
      if (this.isAudio) {
/*        this.fileList = this.value.map(f => {
          return {response: f, url: f}
        });*/
        this.dialogAudioUrl = this.value;

      } else {
        this.dialogImageUrl = this.value;
      }
    },
    watch: {
      value:{
        deep: true,
        handler(val){
          if((typeof val) === "string"){
            this.dialogImageUrl = val;
            this.dialogAudioUrl = val;
          }
        }
      }
    },
    methods: {
      getDuration(url) {

        var audioElement = new Audio(url);
        audioElement.addEventListener("loadedmetadata",(_event)=>{

          let minute =  parseInt(parseInt(audioElement.duration) / 60)
          let seconds = parseInt(audioElement.duration) % 60;
          if (minute < 10) {
            minute = '0' +minute
          }
          if (seconds < 10) {
            seconds = '0' + seconds
          }
          let audioDuration = minute +"."+ seconds;

          this.$emit("getDuration",audioDuration)
          console.log("音频的时长" + audioDuration)
        })
      },
      async handleUpload(params) {

        const that = this;

        const file = params.file;
        const fileType = file.type;
        console.log(file.type)
        const isImage = fileType.indexOf('image') !== -1;
        const isAudio = fileType.indexOf('audio') !== -1;

        //文件的名称
        that.audioName = file.name;
        const isLt20M = file.size < 20 * 1024 * 1024;

        if (!isLt20M) {
          console.log('上传图片或视频大小不能超过 20MB!');
          return;
        }

        //如果上传的是图片，则判断上传的是否是图片,上传的是音乐文件则判断是否是音乐文件
        if (!this.isAudio) {
          if (!isImage) {
            console.log('请选择图片!');
            return;
          }
        }else {
          if (!isAudio) {
            console.log('请选择音乐文件!');
            return;
          }
        }

        // 准备文件名称
        let filename = file.name;
        //向后端发送请求获取签名的地址
        let uploadUrl = this.url;
        // 准备上传表单
        const formData = new FormData();
        // 判断上传到哪里  判断needSignature是否为true，true代表需要签名，false代表不需要
        if (this.needSignature) {
          // 上传到阿里，进行签名，把接收到的url作为签名接口地址
          const resp = await this.$http.loadData(this.url);
          // 判断接口返回的签名时间是否超时
          if (resp.expire < new Date().getTime()) {
            console.log('请求超时!');
            return;
          }
          // 修改文件名为随机文件名
          filename = fileUtil.getFileName(file.name, resp.dir);
          // 修改上传文件路径
          uploadUrl = resp.host;
          // 准备请求参数
          formData.append("key", filename);  //文件的名称
          formData.append("policy", resp.policy);
          formData.append("OSSAccessKeyId", resp.accessId);
          formData.append("success_action_status", '200');
          formData.append("signature", resp.signature);
        }
        formData.append("file", file);

        //上传到阿里oss
        this.$http.post(uploadUrl, formData,
                {
                  headers: {'Content-Type': 'multipart/form-data'},
                  onUploadProgress: function (p) {
                    that.progress = Math.floor((p.loaded / p.total) * 100);
                    console.log(this.progress)
                  }
                })
          .then(resp => {
            console.log(resp);
            if (resp.status == '200') {
              // 获取文件路径
              const fileUrl = resp.data || uploadUrl + "/" + filename;
              // 判断是音乐文件还是图片文件
              if (!this.isAudio) {
                // 图片文件，直接获取地址即可；
                this.dialogImageUrl = fileUrl;
                this.$emit("input", fileUrl)
              } else {
                this.dialogAudioUrl = fileUrl;
                //获取音频时长
                this.getDuration(fileUrl)
                this.$emit("input", fileUrl)
             /*   // 多文件，放到集合中
                const files = this.$refs.multiUpload.uploadFiles;
                files[files.length - 1].response = fileUrl;
                this.fileList = files;
                this.$emit("input", files.map(f => f.response))*/
              }
            } else {
              console.log('上传失败');
            }
          }).catch(function (err) {
          console.log('上传失败');
          console.log(err);
        });
      },
      handleRemove(file, fileList) {
        this.fileList = fileList;
        this.$emit("input", fileList.map(f => f.response))
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.response;
        this.show = true;
      },
      removeSingle() {
        this.dialogImageUrl = "";
        this.$refs.picUpload.clearFiles();
      },
      removeAudio() {
        this.dialogAudioUrl = "";
        this.$refs.audioUpload.clearFiles();
      }
    }
  }
</script>

<style scoped>
  .logo-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    float: left;
  }

  .logo-uploader:hover {
    border-color: #409EFF;
  }

  .logo-uploader-icon {
    font-size: 70px;
    color: #8c939d;
    text-align: center;
  }

  .remove-btn {
    position: absolute;
    right: 0;
    font-size: 16px;
  }

  .remove-btn:hover {
    color: #c22;
  }

  .label_clas{
    color: #8c939d;
    position: absolute;
    margin-top: 40px;
    left: 70px;
    height: 100px;
    font-size: 1.3em;
    display: inline-block;
  }
  .avator_label {
    position: absolute;
    color: gainsboro;
    margin-top: 70px;
    margin-left: 20px;
  }
</style>
